<template>
  <view class="patient-circle-page">
    <!-- 顶部头图与头像 -->
    <view class="header">
      <!-- 自定义返回按钮 -->
      <view class="nav" @click.stop>
        <view class="back-btn" @click.stop="goBack"><text class="back-icon">‹</text></view>
      </view>
      <image class="banner" :src="bannerUrl" mode="aspectFill"></image>
      <view class="avatar-box">
        <image class="avatar" :src="profile.avatar || defaultAvatar" mode="aspectFill"></image>
        <text class="name">{{ profile.username || '患者' }}</text>
      </view>
    </view>

    <view class="section-title">他发布的病友圈</view>

    <!-- 帖子列表（左滑删除） -->
    <scroll-view scroll-y class="list" :lower-threshold="60" @scrolltolower="onScrollToLower">
      <uni-swipe-action>
        <uni-swipe-action-item
          v-for="(post, idx) in posts"
          :key="post.id"
          :right-options="rightOptions"
          @click="onSwipeClick($event, post, idx)"
        >
          <view class="post-item" @click="viewPostDetail(post)">
            <view class="post-title">{{ post.title }}</view>
            <view class="post-meta">
              <text class="time">{{ post.time }}</text>
              <text class="meta">收藏 {{ post.collectNum || 0 }}</text>
              <text class="meta">建议 {{ post.commentNum || 0 }}</text>
            </view>
            <view v-if="post.images && post.images.length" class="thumbs">
              <image v-for="(img, i2) in post.images" :key="i2" :src="img" class="thumb" mode="aspectFill" />
            </view>
            <view class="post-content">{{ post.content }}</view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>

      <view v-if="!posts.length && loaded" class="empty">暂无该患者发布的病友圈</view>
    </scroll-view>
  </view>
</template>

<script>
import { getPatientCircleInfo, deleteMyCircle } from '@/api/circle'

export default {
  data() {
    return {
      defaultAvatar: 'https://img.cdn.aliyun.dcloud.net.cn/uni-app/uniCloud/uni-id/avatar.png',
      patientId: '',
      bannerUrl: 'https://img.yzcdn.cn/vant/cat.jpeg',
      profile: {},
      posts: [],
      loaded: false,
      rightOptions: [
        {
          text: '删除',
          style: {
            backgroundColor: '#f56c6c',
            color: '#fff'
          }
        }
      ]
    }
  },
  onLoad(options) {
    const pid = options && (options.patientId || options.pid)
    this.patientId = pid
    // 先从路由与本地缓存回填头像与昵称，提升首屏展示
    try {
      const prof = { ...this.profile }
      if (options) {
        if (options.username) {
          let n = options.username
          try { n = decodeURIComponent(n) } catch (_) {}
          prof.username = n
        }
        if (options.avatar || options.avatarUrl) {
          let raw = options.avatar || options.avatarUrl
          try { raw = decodeURIComponent(raw) } catch (_) {}
          prof.avatar = this.normalizeUrl(raw) || this.defaultAvatar
        }
      }
      if ((!prof.avatar || prof.avatar === this.defaultAvatar) && pid != null && pid !== '') {
        const KEY = 'patient:profile:map'
        try {
          const cache = uni.getStorageSync(KEY) || {}
          const byPid = cache[String(pid)]
          if (byPid) prof.avatar = this.normalizeUrl(byPid)
        } catch (_) {}
      }
      this.profile = {
        username: prof.username || this.profile.username || '患者',
        avatar: prof.avatar || this.defaultAvatar
      }
    } catch (_) {}
    // 然后拉取数据
    this.fetchData()
  },
  methods: {
    normalizeUrl(url) {
      if (!url) return ''
      try {
        const u = decodeURIComponent(url)
        if (/^https?:\/\//i.test(u)) return u
        // 兼容相对路径
        return u.startsWith('/') ? u : ('/' + u)
      } catch (_) { return url }
    },
    mapCircleToPost(circle) {
      const userObj = circle.user || circle.patient || circle.creator || {}
      const userAvatar = (
        userObj?.avatar || userObj?.avatarUrl || userObj?.headImg || userObj?.headPortrait ||
        circle?.userAvatar || circle?.avatar || circle?.avatarUrl || circle?.headImg || circle?.headPortrait
      )
      // 适配多种图片字段与字符串逗号分隔
      let pics = circle.images || circle.imgList || circle.picUrls || circle.pics || circle.imagesList || circle.img || circle.image || circle.cover || []
      if (typeof pics === 'string') {
        pics = pics.split(/[\s,|;]+/).filter(Boolean)
      }
      const images = Array.isArray(pics) ? pics.map(this.normalizeUrl) : []
      return {
        id: circle.circleId || circle.id,
        title: circle.title || circle.topic || circle.subject || '',
        content: circle.content || circle.text || circle.desc || '',
        time: circle.createTime || circle.createtime || circle.time || circle.publishTime || '',
        commentNum: circle.commentNum || circle.comments || circle.replyCount || circle.adviceCount || 0,
        collectNum: circle.collectNum || circle.collectCount || circle.fav || circle.likeCount || 0,
        userAvatar: this.normalizeUrl(userAvatar) || this.defaultAvatar,
        username: userObj?.nickName || userObj?.name || circle.username || '患者',
        images
      }
    },
    async fetchData() {
      if (!this.patientId) {
        this.loaded = true
        return
      }
      try {
        const res = await getPatientCircleInfo(this.patientId)
        try { console.log('[patient-circle] raw response =', JSON.parse(JSON.stringify(res))) } catch (_) { try { console.log('[patient-circle] raw response (string)=', String(res)) } catch(__) {} }
        let rows = []
        if (Array.isArray(res?.data)) {
          rows = res.data
        } else if (res?.data && typeof res.data === 'object') {
          rows = [res.data]
        } else if (Array.isArray(res?.rows)) {
          rows = res.rows
        } else if (res && typeof res === 'object' && Array.isArray(res)) {
          rows = res
        }
        try { console.log('[patient-circle] pid=', this.patientId, 'rows.len=', rows.length) } catch (_) {}
        // 注意：直接传递 this.mapCircleToPost 会丢失 this 上下文
        this.posts = rows.map(item => this.mapCircleToPost(item))
        // 基础资料（头像/昵称）尝试从首条数据中取
        const first = rows && rows[0] || {}
        const userObj = first.user || first.patient || {}
        const newName = userObj?.nickName || userObj?.name || first.username
        const newAvatar = this.normalizeUrl(
          userObj?.avatar || userObj?.avatarUrl || userObj?.headImg || userObj?.headPortrait
        )
        this.profile = {
          username: newName || this.profile.username || '患者',
          avatar: newAvatar || this.profile.avatar || this.defaultAvatar
        }
      } catch (e) {
        this.$modal && this.$modal.msg && this.$modal.msg('获取该患者的病友圈失败')
        console.error('fetch patient circles error', e)
      } finally {
        this.loaded = true
      }
    },
    onScrollToLower() {
      // 独立页一次性加载，不分页
    },
    viewPostDetail(post) {
      if (!post || post.id === undefined || post.id === null) return
      const url = `/pages/community/detail?id=${encodeURIComponent(post.id)}&patientId=${encodeURIComponent(this.patientId)}&avatar=${encodeURIComponent(post.userAvatar)}`
      uni.navigateTo({ url })
    },
    goBack() { uni.navigateBack() },
    async onSwipeClick(e, post, idx) {
      // e.content 为被点击的按钮配置
      try {
        if (!post || post.id == null) return
        const res = await new Promise(resolve => {
          uni.showModal({
            title: '确认删除',
            content: '删除后不可恢复，是否继续？',
            confirmText: '删除',
            confirmColor: '#f56c6c',
            success: resolve
          })
        })
        if (!res || !res.confirm) return
        uni.showLoading({ title: '删除中', mask: true })
        await deleteMyCircle(post.id)
        // 本地移除，避免整页刷新
        this.posts.splice(idx, 1)
        uni.showToast({ title: '删除成功', icon: 'success' })
      } catch (err) {
        console.error('delete circle failed', err)
        uni.showToast({ title: '删除失败', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.patient-circle-page { min-height: 100vh; background: #f7f8fa; }
.header { position: relative; height: 160px; }
.nav { position: absolute; left: 0; right: 0; top: 0; height: 44px; padding-left: 8px; display:flex; align-items:center; z-index: 5; }
.back-btn { width: 32px; height: 32px; border-radius: 16px; background: rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; }
.back-icon { color:#fff; font-size: 20px; line-height: 1; transform: translateY(-1px); }
.banner { width: 100%; height: 160px; object-fit: cover; }
.avatar-box { position: absolute; left: 16px; bottom: 12px; display:flex; align-items:center; z-index: 6; }
.avatar { width: 56px; height: 56px; border-radius: 50%; border: 2px solid #fff; box-shadow: 0 2px 8px rgba(0,0,0,.15); }
.name { margin-left: 10px; font-weight: 600; color: #fff; font-size: 16px; line-height: 1; padding: 6px 10px; background: rgba(0,0,0,.35); border-radius: 14px; backdrop-filter: blur(2px); text-shadow: 0 1px 2px rgba(0,0,0,.3); }
.section-title { margin: 12px 16px 8px; color:#5a6; font-size: 14px; border-left:3px solid #5ac; padding-left:8px; background: #fff; height: 44px; line-height: 44px; border-radius: 8px; padding-left: 10px; }
.list { min-height: calc(100vh - 220px); padding: 8px 16px; box-sizing: border-box; }
.post-item { background: #fff; border-radius: 8px; padding: 12px; margin-bottom: 12px; }
.post-title { font-size: 16px; font-weight: 600; color: #333; }
.post-meta { margin-top: 6px; color: #999; font-size: 12px; display:flex; gap:12px; }
.thumbs { display:flex; gap:6px; margin-top:8px; }
.thumb { width: 90px; height: 90px; border-radius: 6px; background:#f2f3f5; }
.post-content { margin-top: 8px; color: #555; font-size: 14px; }
.empty { text-align:center; color:#999; padding: 24px 0; }
</style>
